package com.css.zfzx.sjcj.common.utils;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

public class ServerUtil {

    //终极质检员
    static String ultimateQC = "ultimate";
    //普通质检员
    static String ordinaryQc = "ordinary";

    /**
     * 判断某用户是否存在角色
     *
     * @param roleEntities
     * @param code
     * @return
     */
    public static boolean isContaintRole(List<RoleEntity> roleEntities, String code) {
        boolean flag = false;
        for (RoleEntity role : roleEntities) {
            if (code.equals(role.getRoleCode())) {
                flag = true;
                break;
            }
        }
        if (flag) {
            return true;
        } else {
            return false;
        }
    }

    public static void addErrorMsg(StringBuilder builder, String field, String msg) {
        builder.append(field);
        builder.append(": ");
        builder.append(msg);
        builder.append("; ");
    }

    public static void addNullMsg(StringBuilder builder, String field) {
        ServerUtil.addErrorMsg(builder,field,"为空");
    }

    /**
     * 根据属性，获取get方法
     * @param ob 对象
     * @param name 属性名
     * @return
     * @throws Exception
     */
    public static Object getGetMethod(Object ob , String name)throws Exception{
        Method[] m = ob.getClass().getMethods();
        for(int i = 0;i < m.length;i++){
            if(("get" + name).toLowerCase().equals(m[i].getName().toLowerCase())){
                return m[i].invoke(ob);
            }
        }
        return null;
    }

    public static void checkFieldNull(Object ob, Map<String,String> methodNames, StringBuilder builder) throws Exception{
        if(PlatformObjectUtils.isEmpty(ob) || PlatformObjectUtils.isEmpty(methodNames) || PlatformObjectUtils.isEmpty(builder)){
            return;
        }

        for(Map.Entry<String,String> entry : methodNames.entrySet()){
            if(PlatformObjectUtils.isEmpty(ServerUtil.getGetMethod(ob,entry.getKey()))){
                addNullMsg(builder,entry.getValue());
            }
        }
    }

    /**
     *  判断当前用户是否是终极质检员
     *
     * @return 是否终检员
     */
    public static boolean isUltimateQc(){
        String userId = PlatformSessionUtils.getUserId();
        if(null == userId){
            return false;
        }
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);

        return isContaintRole(roles,ServerUtil.ultimateQC);
    }

    public static String getQcFieldString(){
        return isUltimateQc() ? "3" : "2";
    }
}
